import 'package:flutter/material.dart';
import 'package:safety_platform/models/risk.dart';
import 'package:safety_platform/models/classification.dart';
import 'package:safety_platform/models/attachment.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:safety_platform/iconfont.dart';
import 'package:safety_platform/models/hidden_danger.dart';
import 'package:safety_platform/models/situation.dart';
import 'package:safety_platform/models/risk_unit.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:io';
import 'package:safety_platform/pages/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:safety_platform/components/attachment.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:safety_platform/components/tree_selection.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:safety_platform/theme.dart';

class CreateHiddenDangerPgae extends StatefulWidget {
  final Risk risk;
  final List<Attachment> attachments;
  final String content;
  final String traceNo;

  CreateHiddenDangerPgae(
      {this.risk, this.content, this.attachments, this.traceNo});

  @override
  State<StatefulWidget> createState() =>
      _HiddenDangerState(this.risk, this.attachments, this.content);
}

class TaskItemHiddenDangerPage extends CreateHiddenDangerPgae {
  final String taskId;
  final String itemId;
  TaskItemHiddenDangerPage(this.taskId, this.itemId,
      {risk, content, attachments, traceNo})
      : super(
            risk: risk,
            content: content,
            attachments: attachments,
            traceNo: traceNo);

  State<StatefulWidget> createState() => _TaskItemHiddenDangerState(
      this.taskId, this.itemId, risk, attachments, content);

  //=> _TaskItemHiddenDangerState(taskId,
  //itemId, this.risk, attachments,memo);
}

class _TaskItemHiddenDangerState extends _HiddenDangerState {
  String itemId;
  String taskId;
  _TaskItemHiddenDangerState(this.taskId, this.itemId, Risk risk,
      List<Attachment> attachments, String memo)
      : super(risk, attachments, memo);

  @override
  void onSubmit(HiddenDangerRequest hd) {
    TaskHiddenDangerRequest hr = TaskHiddenDangerRequest.copyForm(hd);

    hr.itemId = this.itemId;
    submitTaskHiddenDanger(this.taskId, hr).then((HiddenDanger hd) {
      Fluttertoast.showToast(
        msg: '提交成功',
      );
      setState(() {
        _submitting = false;
      });
      Navigator.of(context).pop(hd);
    }).catchError((err) {
      print(err.message);
      print(err.response.data);
      setState(() {
        _submitting = false;
      });
    });
  }
}

class _HiddenDangerState extends State<CreateHiddenDangerPgae> {
  String _level;
  bool _selected;
  TreeNode _classification;
  bool _submitting = false;
  Risk risk;
  _HiddenDangerState(this.risk, this.attachments, this.memo);
  List<Attachment> attachments;
  String memo;
  List<Situation> _situations = [];
  List<RiskUnit> riskUnits;
  TextEditingController _memoController;
  TextEditingController _controller;
  SlidableController _slidableController;


  void _showPopDialog(String title, VoidCallback onConfirm) {
    // _controller.clear();
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            actions: <Widget>[
              // RaisedButton(child: Text('取消'),),
              RaisedButton(
                onPressed: () {
                  onConfirm();
                  Navigator.of(context).pop();
                },
                color: Theme.of(context).primaryColor,
                child: Text(
                  '确认',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              )
            ],
            title: Center(child: Text(title)),
            contentPadding: EdgeInsets.all(16),
            content: SingleChildScrollView(
              child: Container(
                color: Colors.white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        // Expanded(flex: 1, child: Text('整改描述')),
                        Expanded(
                          flex: 2,
                          child: TextField(
                            controller: _controller,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.all(8),
                              hintText: '请输入问题描述，150字以内',
                              hintStyle: TextStyle(
                                fontSize: 14,
                              ),
                              // labelText: '整改描述',
                              border: InputBorder.none,
                              // border: OutlineInputBorder(
                              //     gapPadding: 0,
                              //     borderSide: BorderSide(
                              //       color: Color.fromARGB(255, 241, 241, 241),
                              //       width: 0.5,
                              //     ),
                              //     borderRadius: BorderRadius.circular(2.0)),
                            ),
                            maxLength: 150,
                            maxLines: 5,
                            textInputAction: TextInputAction.done,
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
            // children: <Widget>[
            //       // Text('整改描述'),
            //       TextField(
            //         decoration: InputDecoration(
            //           labelText: '整改描述',
            //           border: OutlineInputBorder(),
            //         ),

            //         maxLines: 4,
            //         maxLength: 150,
            //         textInputAction: TextInputAction.done,
            //       )
            //       ,
            //       SimpleDialogOption(child: Text('确定'),),
            //       SimpleDialogOption(child: Text('确定'),)

            //     ],
          );
          // Text('整改类型'),
          // Checkbox(value: 2,)
        }).then((value) {
      _controller.clear();
    });
  }

 

  _buidlLevelWidget() {
    TextStyle style;
    if (_level == null) {
      _level = '请选择隐患级别';
      style = TextStyle(color: Colors.grey);
    }

    Widget levelWidget = InkWell(
      child: Text(_level, style: style),
      onTap: () => showDialog(
          context: context,
          builder: (context) {
            return singleListDialog(context, title: null, fn: (s) {
              setState(() {
                _level = s;
              });
            });
          }),
    );

    if (_level == null) {}
    return Container(
      padding: EdgeInsets.all(16),

      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(255, 241, 241, 241),
          ),
        ),
      ),
      // color: Colors.red,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text('隐患级别'),
          levelWidget,
        ],
      ),
    );
  }

  _buildRiskWidget() {
    Widget riskWidget;

    if (risk != null) {
      riskWidget = InkWell(
        child: Text(
          risk.name,
          textAlign: TextAlign.right,
          overflow: TextOverflow.ellipsis,
        ),
        onTap: () => _selectRisk(),
      );
    } else {
      riskWidget = InkWell(
        child: Text(
          '请选择风险点',
          style: TextStyle(color: Colors.grey),
          textAlign: TextAlign.right,
          overflow: TextOverflow.ellipsis,
        ),
        onTap: () => _selectRisk(),
      );
    }
    return Container(
      padding: EdgeInsets.all(16),

      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: 1,
            color: Color.fromARGB(255, 241, 241, 241),
          ),
        ),
      ),
      // color: Colors.red,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Expanded(child: Text('风险点')),
          Expanded(child: riskWidget),
          // GestureDetector(
          //   child: Text('请选择风险单元'),
          // )
        ],
      ),
    );
  }

  Future<List<TreeNode>> _fetchAndtransferClassfication(TreeNode node) async {
    print("form future");
    List<Classification> classficiations =
        await loadClassification(code: node.code);

    List<TreeNode> treeNodes = classficiations.map((c) {
      return TreeNode(c.code, c.name);
    }).toList();

    return Future.value(treeNodes);
  }

  _selectRisk() {
    List<TreeNode> children = riskUnits.map((f) {
      TreeNode node = TreeNode(f.id.toString(), f.unitName);
      node.children = f.risks
          .map((risk) => TreeNode(risk.id.toString(), risk.name))
          .toList();
      return node;
    }).toList();
    showDialog(
        context: context,
        builder: (_) => SimpleDialog(
              contentPadding: EdgeInsets.all(0),
              children: <Widget>[
                TreeSelectionWidget(children, (TreeNode node) {
                  Risk risk;
                  for (RiskUnit u in riskUnits) {
                    for (Risk rr in u.risks) {
                      if (rr.id.toString() == node.code) {
                        risk = rr;
                        break;
                      }
                    }
                  }
                  setState(() {
                    this.risk = risk;
                  });
                })
              ],
            ));
  }

  Future<List<TreeNode>> _fetchClassfication(TreeNode node) {
    print('load classfication: ${node.code}, ${node.title}');

    return _fetchAndtransferClassfication(node);
    // return Future<List<TreeNode>>((){
    //   return _fetchAndtransferClassfication;
    // });
    // return loadClassification(code:node.code).then((_)
    // ).then((a) {

    // });
    // return Future<List<TreeNode>>(() {
    //   loadClassification(code: node.code)
    //       .then((List<Classification> classficiations) {
    //     List<TreeNode> treeNodes = classficiations.map((c) {
    //       return TreeNode(c.code, c.name);
    //     }).toList();
    //     return treeNodes;
    //     // return Future.value(treeNodes);
    //   });
    // });
    //  return _fetchAndtransferClassfication(node);
  }

  void _onClassificationSelection(TreeNode node) {
    print('当前选择 $node');
    setState(() {
      this._classification = node;
    });
  }

  void _onClassficationTaped() {
    if (risk == null) {
      //提示先选择风险点
      Fluttertoast.showToast(
        msg: '请选择风险点',
      );
      return;
    }
    List<TreeNode> treeNode = risk.classification.map((c) {
      return TreeNode(c.code, c.name);
    }).toList();

    showDialog(
        context: context,
        builder: (_) => SimpleDialog(
              contentPadding: EdgeInsets.all(0),
              titlePadding: EdgeInsets.all(0),
              children: <Widget>[
                AsyncTreeSeletctionWidget(
                    treeNode, _fetchClassfication, _onClassificationSelection),
              ],
            ));
  }

  Widget _buildClassficitions() {
    Widget rightWidget;

    if (this._classification != null) {
      rightWidget = Text(
        this._classification.title,
      );
    } else {
      rightWidget = Text('请选择隐患类别',
          style: TextStyle(
            color: Colors.grey,
          ));
    }
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(255, 241, 241, 241),
          ),
        ),
      ),
      // color: Colors.red,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text('隐患类别'),
          InkWell(
            onTap: () => _onClassficationTaped(),
            child: rightWidget,
          )
        ],
      ),
    );
  }

  void _editSituation(s) {
    _controller.text = s.content;

    _showPopDialog(
        '编辑隐患问题',
        () => setState(() {
              s.content = _controller.text;
            }));
  }

  void _addSituation() {
    _controller.clear();
    _showPopDialog('新增隐患问题', () {
      if (_controller.text == null || _controller.text.length <= 0) {
        return;
      }
      setState(() {
        _situations.add(Situation(this._controller.text));
      });
    });
  }

  Widget _buildSituationWidget() {
    List<Widget> children = [
      backgroundTitle('发现的问题'),
    ];
    int index = 0;
    List<Widget> situationWidgets = _situations.map((s) {
      ++index;
      return DecoratedBox(
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: Slidable(
          delegate: SlidableStrechDelegate(),
          controller: _slidableController,
          actionExtentRatio: 0.25,
          secondaryActions: <Widget>[
            IconSlideAction(
              caption: '编辑',
              color: Colors.blue,
              icon: Icons.edit,
              onTap: () {
                // _controller.text = s;
                _editSituation(s);
              },
            ),
            IconSlideAction(
                caption: '删除',
                color: Colors.red,
                icon: Icons.delete,
                onTap: () {
                  setState(() => _situations.remove(s));
                }),
          ],
          child: ListTile(
            title: Text('$index. ${s.content}'),
          ),
        ),
      );
    }).toList();

    situationWidgets.add(DecoratedBox(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: ListTile(
        title: InkWell(
          child: Text(
            '增加一个问题',
            style: TextStyle(
              color: Colors.blue,
              decoration: TextDecoration.underline,
            ),
          ),
          onTap: () => this._addSituation(),
        ),
      ),
    ));
    children.addAll(
        ListTile.divideTiles(context: context, tiles: situationWidgets));
    return Container(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    ));
  }

  _body(BuildContext context) {
    return SingleChildScrollView(
        child: Container(
      // color: Color.fromARGB(255, 245, 245, 249),

      width: MediaQuery.of(context).size.width,
      // padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _buildRiskWidget(),
          _buildClassficitions(),
          _buidlLevelWidget(),
          _buildSituationWidget(),
          backgroundTitle('问题照片'),
          AttachmentGallery(
            backgoundColor: Colors.white,
            onTakePhoto: () {
              ImagePicker.pickImage(source: ImageSource.camera).then((file) {
                if (file != null) {
                  Attachment attachment = Attachment.fromLocal(file.path, file.path);
                  if (mounted) {
                    setState(() {
                      attachments
                          .add(attachment);
                    });
                    uploadAttachment(attachment,target: 'risk.SituationImage').then(
                      (attach) {
                        if (mounted) {
                         
                          setState((){
                             attachment.id = attach.id;
                             attachment.url = attach.url;
                              attachment.uploadStatus = 'done';
                          }) ;

                        }
                      }
                    );
                  }
                }
              });
            },
            attachments: attachments,
            uploadLabel: '拍摄问题照片',
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: 40,
            margin: EdgeInsets.symmetric(vertical: 16),
            padding: EdgeInsets.fromLTRB(32, 0, 32, 0),
            child: RaisedButton(
                color: Colors.red,
                onPressed: () => _submit(),
                textColor: Colors.white,
                child: !_submitting
                    ? Text('隐患提交')
                    : SpinKitWave(
                        color: Colors.white,
                        size: 16,
                      )),
          )
        ],
      ),
    ));
  }

  _showError(String error) {
    showDialog(
        context: context,
        builder: (BuildContext conext) {
          return AlertDialog(
            // contentPadding: EdgeInsets.all(0),
            title: Text('错误'),
            content: Text(error),
            // actions: <Widget>[
            //   FlatButton(child: Text('确定'),onPressed: ()=>Navigator.pop(context),),
            // ],
          );
        });
  }

  onSubmit(HiddenDangerRequest hd) {
    submitHiddenDanger(hd).then((HiddenDanger nhd) {
      Fluttertoast.showToast(
        msg: '提交成功',
      );
      setState(() {
        _submitting = false;
      });
      Navigator.of(context).pop(nhd);
    }).catchError((err) {
      print(err.message);
      // print(err.response.data);
      setState(() {
        _submitting = false;
      });
    });
  }

  _submit() {
    if (_submitting) {
      return;
    }
    if (risk == null) {
      _showError('请选择风险点');
      return;
      // child: AboutDialog(children:[Text('请选择风险点')]));
    }
    if (_classification == null) {
      _showError('请选译隐患类别');
      return;
    }
    if (_level == null) {
      _showError('请选择隐患级别');
      return;
    }
    if (_situations == null || _situations.length <= 0) {
      _showError('请至少增加一个隐患问题');
      return;
    }

    int index = 0;
    for (Situation situation in _situations) {
      situation.orderKey = ++index;
    }

    // if (memo == null) {
    //   _showError('请填写隐患描述');
    //   return;
    // }

    setState(() {
      _submitting = true;
    });
    HiddenDangerRequest danger = HiddenDangerRequest();

    danger.riskId = risk.id;
    danger.classificationId = _classification.code;
    danger.status = 'created';
    danger.grade = hiddenDangerGradeToCode(_level);
    danger.memo = memo;
    danger.source = 'C';
    danger.traceNo = widget.traceNo ?? '';
    danger.situationImages = attachments;
    danger.situations = _situations;
    onSubmit(danger);
  }


  @override
  void initState() {
    _selected = false;
    fetchAllRiskUnit().then((List<RiskUnit> units) {
      this.riskUnits = units;
    });
    if (this.attachments == null) {
      this.attachments = List();
    }
    // if (this.memo != null) {
    //   this._memoController.addListener(listener)
    // }
    this._memoController = TextEditingController();
    if (this.memo != null) {
      this._memoController.text = this.memo;
    }
    _slidableController = SlidableController();

    this._controller = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _memoController.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: new Text("隐患登记"),
        elevation: 0,

        //     leading: appLeading(context),
        // backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      body: _body(context),
    );
  }

  List<String> dangerLevel = ['重大事故隐患', '一般事故隐患', '轻微事故隐患'];
  Widget singleListDialog(BuildContext context,
      {String title, List<String> child, Function(String) fn}) {
    Widget titleWidget;
    if (title != null) {
      titleWidget = Container(
        width: MediaQuery.of(context).size.width,
        child: Center(child: Text('隐��级别')),
      );
    }
    return SimpleDialog(
        title: titleWidget,
        contentPadding: EdgeInsets.all(0),
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: dangerLevel.map((f) {
              return GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                  if (fn != null) {
                    fn(f);
                  }
                },
                child: Container(
                  // height: 50,
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Color.fromARGB(255, 241, 241, 241),
                      ),
                    ),
                  ),
                  child: Text(f),
                ),
              );
            }).toList(),
          ),
        ]);
  }
}
